# -*- coding: utf-8 -*-
import KBEngine
import IKernel
import MsgDef
import ErrorCodeDef
import ConstDef
import NameModDef
import time
import random
import LogDef

from KBEDebug import *

class NameModule:
	def __init__(self):
		pass

	def init(self, isReload):
		IKernel.Instance().registerFunc("NameModule.onBaseMsg", self.onBaseMsg)
		IKernel.Instance().registerFunc("NameModule.onClientMsg", self.onClientMsg)

		IKernel.Instance().addIntMsgCallback(MsgDef.BASE2CELL_NAME_MSG, "NameModule.onBaseMsg")
		IKernel.Instance().addIntMsgCallback(MsgDef.CLIENT2CELL_NAME_MSG, "NameModule.onClientMsg")

	def end(self):
		pass

	def onBaseMsg(self, senderEntityID, receiverEntityID, args):
		dispatcher = {
			NameModDef.SUB_MSG_CHANGE_NAME : self.saveNameResult,
		}
		submsg = args[1]
		funcAddr = dispatcher.get(submsg)
		if funcAddr == None:
			return
		funcAddr(receiverEntityID, args)

	def saveNameResult(self, playerEntityID, args):
		isSuc = args[2]
		newName = args[3]
		DEBUG_MSG("NameModule.saveNameResult isSuc=%d, newName=%s"% (isSuc, newName))
		if isSuc == False:
			msg = []
			msg.append(MsgDef.CELL2CLIENT_NAME_MSG)
			msg.append(NameModDef.SUB_MSG_CHANGE_NAME)
			msg.append(ErrorCodeDef.AlreadyExistName)
			msg.append(newName)
			IKernel.Instance().sendClientMsg(playerEntityID, msg)
			return

		playerEntity = KBEngine.entities.get(playerEntityID)
		# 扣道具
		if playerEntity.changeNameCount > 0:
			from logic import ModuleMgr
			itemModule = ModuleMgr.Instance().getModule("ItemModule")
			itemModule.subItem(playerEntityID, 0, NameModDef.CHANGE_NAME_NEED_ITEM, 1,LogDef.SUB_LOG_CHANGE_NAME_CONSUME)

		playerEntity.changeNameCount += 1
		playerEntity.name = newName
		playerEntity.writeToDB()

		msg = []
		msg.append(MsgDef.CELL2CLIENT_NAME_MSG)
		msg.append(NameModDef.SUB_MSG_CHANGE_NAME)
		msg.append(ErrorCodeDef.No)
		msg.append(newName)
		IKernel.Instance().sendClientMsg(playerEntityID, msg)

	def onClientMsg(self, senderEntityID, receiverEntityID, args):
		dispatcher = {
			NameModDef.SUB_MSG_CHANGE_NAME : self.changeName,
		}
		submsg = args[1]
		funcAddr = dispatcher.get(submsg)
		if funcAddr == None:
			return
		funcAddr(receiverEntityID, args)

	def changeName(self, playerEntityID, args):
		from logic import ModuleMgr
		itemModule = ModuleMgr.Instance().getModule("ItemModule")

		playerEntity = KBEngine.entities.get(playerEntityID)
		if playerEntity.changeNameCount > 0:# 改名字次数大于0，就需要改名道具了
			hasNum = itemModule.getItemNum(playerEntityID, NameModDef.CHANGE_NAME_NEED_ITEM)
			# 改名道具不够
			if hasNum < 1:
				return

		newName = args[2]
		if len(newName) > 32:#名字太长
			return

		msg = []
		msg.append(MsgDef.CELL2BASE_NAME_MSG)
		msg.append(NameModDef.SUB_MSG_CHANGE_NAME)
		msg.append(newName)
		IKernel.Instance().sendBaseMsg(playerEntityID, playerEntityID, msg)
























